package com.example.zuulserver1060.fallback;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 温伟雄
 * @Date: 2021/10/13/13:16
 * @Description:
 */
@Component
public class PayServerFallback implements FallbackProvider {

    private final Logger logger= LoggerFactory.getLogger(PayServerFallback.class);

    //指定要处理的服务，如果要让此熔断功能作用于所有的服务，将 getRoute 方法中的返回值修改为“*”即可
    @Override
    public String getRoute() {
        return "order-server";
    }

    /**
     *
     * @param route 服务的路由
     * @param cause 异常
     * @return ClientHeepRrsponse：熔断后的返回值
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("抱歉，服务不可用".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers=new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
